package cn.jji8.createX.function.wand.canPlaceBlock;

import cn.jji8.createX.function.wand.Wand;
import cn.jji8.createX.slowPlaceBlock.CanPlaceBlock;
import cn.jji8.createX.slowPlaceBlock.SlowPlaceBlockManger;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;

import java.util.*;

public class WandFunction implements CanPlaceBlock {
    public static WandFunctionState start(Player player, Block block, Material replaceMaterial, Wand wand){
        WandFunction wandFunction = new WandFunction();
        WandFunctionState wandFunctionState = new WandFunctionState(player,replaceMaterial,block.getType(),wand,wandFunction);
        //给iterationWandFunctionBook添加第一个任务
        Set<WandFunctionBook> set = new HashSet<>();
        set.add(new WandFunctionBook(block,wandFunctionState));
        wandFunction.wandFunctionState = wandFunctionState;
        wandFunction.wandFunctionBookList = set;
        SlowPlaceBlockManger.addSoonPlaceBlock(wandFunction);
        return  wandFunctionState;
    }
    //填充管理器
    WandFunctionState wandFunctionState;
    //任务列表
    Set<WandFunctionBook> wandFunctionBookList = new HashSet<>();
    //上一个列表的迭代器
    Iterator<WandFunctionBook> iterationWandFunctionBook = null;
    //即将反馈给玩家的消息
    String sendMessage = null;
    public WandFunction() {
    }
    /**
     * 用于在指定位置放置方块的方法
     *
     * @return 下一个需要填充的方块
     */
    @Override
    public CanPlaceBlock place(){
        CanPlaceBlock canPlaceBlock = place(0);
        if(canPlaceBlock==null){
            wandFunctionState.setCancel(true);
        }
        if(sendMessage!=null){
            SlowPlaceBlockManger.sendMessage(wandFunctionState.player,sendMessage);
            sendMessage = null;
        }
        return canPlaceBlock;
    }

    public CanPlaceBlock place(int i) {
        //如果已经被取消
        if(wandFunctionState.isCancel()){
            return null;
        }
        if(iterationWandFunctionBook==null){
            iterationWandFunctionBook = wandFunctionBookList.iterator();
            wandFunctionBookList = new HashSet<>();
        }
        if(iterationWandFunctionBook.hasNext()){
            sendMessage = "§d魔棒工具正在工作,已为你替换§e"+wandFunctionState.count+"§d个方块。";
            List<WandFunctionBook> list = iterationWandFunctionBook.next().dig();
            if(list==null){
                if(i>50){
                    return this;
                }
                return place(++i);
            }
            wandFunctionBookList.addAll(list);
            return this;
        }else {
            iterationWandFunctionBook = wandFunctionBookList.iterator();
            wandFunctionBookList = new HashSet<>();
            if(!iterationWandFunctionBook.hasNext()){
                return null;
            }else {
                return this;
            }
        }
    }
}
